package com.cn.kehong.service;

import com.cn.kehong.api.IPowRateDetailService;
import com.cn.kehong.dao.PowRateDetailMapper;
import com.cn.kehong.domain.PowRate;
import com.cn.kehong.domain.PowRateDetail;
import com.cn.kehong.domain.PowRateDetailExample;
import com.cn.kehong.utils.CommonUtil;
import com.cn.kehong.utils.Constants;
import com.cn.kehong.utils.QueryForm;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class PowRateDetailServiceImpl implements IPowRateDetailService {

    @Autowired
    private PowRateDetailMapper powRateDetailMapper;

    @Override
    public List<PowRateDetail> getPowRateDetails(String powId) throws Exception {
        if(StringUtils.isEmpty(powId)){
            return Lists.newArrayList();
        }
        PowRateDetailExample example = new PowRateDetailExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andPowIdEqualTo(powId);
        example.setOrderByClause("sort_index asc");
        List<PowRateDetail> powRateDetails = powRateDetailMapper.selectByExample(example);
        return powRateDetails;
    }

    @Override
    public String addPowRateDetail(List<PowRateDetail> powRateDetails) throws Exception {
        if(CollectionUtils.isEmpty(powRateDetails)){
            return "数据为空";
        }
        int count = powRateDetailMapper.batchInsertPowRateDetail(powRateDetails);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updatePowRateDetail(List<PowRateDetail> powRateDetails) throws Exception {
        if(CollectionUtils.isEmpty(powRateDetails)){
            return "数据为空";
        }
        String powId = powRateDetails.get(0).getPowId();
        if(StringUtils.isEmpty(powId)){
            return "主键id为空";
        }
        PowRateDetailExample example = new PowRateDetailExample();
        example.createCriteria().andPowIdEqualTo(powId);
        int count = powRateDetailMapper.deleteByExample(example);
        if(count <0 ){
            return "清理数据异常！";
        }
        count = powRateDetailMapper.batchInsertPowRateDetail(powRateDetails);
        if(count < 1){
            throw new Exception("更新数据异常！");
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public List<PowRateDetail> getCapacityByKb(QueryForm queryForm) throws Exception {
        List<PowRateDetail> powRateDetails = powRateDetailMapper.getCapacityByKb(queryForm);
        return powRateDetails;
    }
}
